const data = {
  "a-0": {
    "0-a-0": null,
    "0-a-1": {
      "0-0-1-0": null,
      "0-0-1-1": null,
      "0-0-1-2": null,
    },
    "0-a-2": null,
  },
  "b-0": {
    "0-b-0": null,
    "0-b-1": null,
  },
  "c-0": null,
};
class TreeControl {
  constructor(data, setData) {
    this.data = data;
    this.setData = setData;
    this.isOpen = true;
  }
  generateDom(data = this.data, parEl) {
    for (let i in data) {
      let currentEl = document.createElement("li");
      if (!data[i]) {
        currentEl.innerHTML = `<input class="checkInp" data-child="true" ${this.setData.select} type="checkbox"></input>${i}`;
      } else {
        currentEl.innerHTML = `
          <span class="dom-wrap">
            <span class="switch" data-open="true"></span>
            <input class="checkInp"  type="checkbox" ${this.setData.select}="alert('ok')"></input>${i}
          </span>
        `;
        let nextParentEl = document.createElement("ul");
        currentEl.appendChild(nextParentEl);
        this.generateDom(data[i], nextParentEl);
      }
      parEl.appendChild(currentEl);
    }
    return parEl;
  }
  initHtml() {
    let parentEl = document.querySelector(this.setData.element);
    this.generateDom(this.data, parentEl);
    let isOpenEl = document.querySelectorAll(".switch");
    let chenkEl = document.querySelectorAll(".checkInp");
    let slef = this;
    isOpenEl.forEach((item) => {
      item.addEventListener("click", function () {
        slef.treeToggle(this);
      });
    });
    chenkEl.forEach((item) => {
      item.addEventListener("click", function () {
        slef.checkElFun(this);
      },false);
    });
  }
  treeToggle(currentEl) {
    let parentEl = currentEl.parentNode.nextElementSibling;
    if (this.isOpen) {
      parentEl.style.display = "none";
      this.isOpen = false;
    } else {
      parentEl.style.display = "block";
      this.isOpen = true;
    }
    currentEl.setAttribute("data-open", this.isOpen);
  }
  checkElFun(currentEl) {
    let eventEl = currentEl.parentNode.nextElementSibling;
    console.log(currentEl);
    if (currentEl.getAttribute("data-child")) return;
    let allCheckBox = eventEl.querySelectorAll("input");
    if (currentEl.checked) {
      allCheckBox.forEach((item) => {
        item.checked = true;
      });
    } else {
      allCheckBox.forEach((item) => {
        item.checked = false;
      });
    }
  }
}
let newTree = new TreeControl(data, {
  element: "#container",
  select: "onselect",
});
newTree.initHtml();
